package org.skatiger.jrove.component.html;

import java.io.IOException;
import java.util.List;

import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.ResponseWriter;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.JroveAttr;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.component.UIComponentBase;
import org.skatiger.jrove.component.UIResource;
import org.skatiger.jrove.component.UIViewRoot;
import org.skatiger.jrove.renderer.Html;
import org.skatiger.jrove.resource.Resource;
import org.skatiger.jrove.resource.ResourceType;

public class HtmlHead extends UIComponentBase {

    @Override
    public void encodeEnd(ViewContext context) throws IOException {
        super.encodeEnd(context);
        UIViewRoot root = context.getViewRoot();
        List<Resource> resources = root.getResources();
        for (Resource resource : resources) {
            renderResource(context, resource);
        }
    }

    private void renderResource(ViewContext context, Resource resource)
            throws IOException {
        if (UIComponent.class.isAssignableFrom(resource.getClass())) {
            renderUIResource(context, (UIComponent) resource);
            return;
        } else if (resource.getType() == ResourceType.Javascript) {
            renderJavascriptResource(context, resource);
            return;
        } else if (resource.getType() == ResourceType.Stylesheet) {
            renderStylesheetResource(context, resource);
            return;
        }
        throw new JroveException("can not supported resource." + resource);
    }

    private void renderUIResource(ViewContext context, UIComponent component)
            throws IOException {
        component.encodeAll(context);
    }

    private void renderJavascriptResource(ViewContext context, Resource resource)
            throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(Html.SCRIPT_ELEM, this);
        writer.writeAttribute(Html.TYPE_ATTR, Html.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
        writer.writeAttribute(Html.SRC_ATTR,
                UIResource.getResourceURL(context, resource.getValue()),
                JroveAttr.VALUE_ATTR);
        writer.endElement(Html.SCRIPT_ELEM);
    }

    private void renderStylesheetResource(ViewContext context, Resource resource)
            throws IOException {

        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(Html.LINK_ELEM, this);
        writer.writeAttribute(Html.REL_ATTR, Html.STYLESHEET_VALUE, null);
        writer.writeAttribute(Html.TYPE_ATTR, Html.STYLE_TYPE_TEXT_CSS, null);
        writer.writeAttribute(Html.HREF_ATTR,
                UIResource.getResourceURL(context, resource.getValue()),
                JroveAttr.VALUE_ATTR);
        //        <link rel="stylesheet" type="text/css" href="theme.css" />
        writer.endElement(Html.LINK_ELEM);
    }

}
